from duckserver.models import Studyrecord, Room, User, Longplan
import time
import datetime
from django.conf import settings

# 新建学习记录 (传入的starttime是秒级时间戳,runtime存分钟)
from duckserver.service.duckPowerEgg import getPower


def createStudyRecord(target,userid,starttime,runtime,iscompleted,failreason,type,planid):
    response = {'recordid': 0, 'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    type = int(type)


    if type == 0:
        runtime = int(runtime)
        starttime_final = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(starttime)))
        record = Studyrecord(target=target, userid=user, starttime=starttime_final,
                             runtime=runtime, iscompleted=iscompleted, failreason=failreason, type=type)
        record.save()
        response['recordid'] = record.recordid
        getPower(userid, runtime / 30)  # runtime  单位是分钟


    elif type == 1:
        runtime = int(runtime)
        starttime_final = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(starttime)))
        record = Studyrecord(target=target, userid=user, starttime=starttime_final,
                             runtime=runtime, iscompleted=iscompleted, failreason=failreason, type=type)
        longplan = Longplan.objects.get(planid=planid)
        st = longplan.studytime
        st += runtime
        # 防止学习时间超过目标时间
        if st >= longplan.targettime:
            longplan.studytime = longplan.targettime
            longplan.isfinished = 1
        else:
            longplan.studytime = st
        longplan.save()
        record.save()
        getPower(userid, runtime / 30)  # runtime  单位是分
        response['recordid'] = record.recordid

    elif type == 2:
        record = Studyrecord(target=target, userid=user, iscompleted=iscompleted, failreason=failreason, type=type)
        room = Room.objects.get(userid=user)
        st = int(time.time())-int(time.mktime(room.jointime.timetuple()))
        st = st//60
        record.runtime = st
        record.starttime = room.jointime

        Room.objects.filter(roomid=room.roomid).update(usercount=room.usercount-1)
        room.delete()
        record.save()
        getPower(userid, st / 30)  # runtime  单位是秒
        response['recordid'] = record.recordid
    else:
        pass
    response['ok'] = 1
    return response


# 单独的一个功能函数，获取当天已经学过的时间，计算自习室学习时长，返回分钟
def getDailyStudyTime(userid):
    now = datetime.datetime.now()
    zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second, microseconds=now.microsecond)
    user = User.objects.get(userid=userid)
    room = Room.objects.filter(userid=user)
    recordList = Studyrecord.objects.filter(userid=user,starttime__gte=zero_today).values('runtime')
    studyTime = 0
    for record in recordList:
        studyTime += record['runtime']
    if len(room) == 0:
        pass
    else:
        jointime = room[0].jointime
        if int(time.mktime(zero_today.timetuple()))-int(time.mktime(jointime.timetuple())) > 0:
            jointime = zero_today
        roomStudyTime = int(time.time())-int(time.mktime(jointime.timetuple()))
        studyTime += roomStudyTime//60
    return studyTime


# 单独的一个功能函数，获取当天已经学过的时间，不计算自习室学习时长，返回分钟
def getDailyStudyTimeRank(userid):
    now = datetime.datetime.now()
    zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second, microseconds=now.microsecond)
    user = User.objects.get(userid=userid)
    recordList = Studyrecord.objects.filter(userid=user,starttime__gte=zero_today,type__lt=2).values('runtime')
    studyTime = 0
    for record in recordList:
        studyTime += record['runtime']
    return studyTime


# 用户学习排行榜
def getStudyRank(page):
    page = int(page)
    response = {'data': 0, 'ok': 0, 'msg': ''}
    userList = User.objects.filter(isadministator=0).values('userid')
    studyTimeList = []
    data = []
    counter = 0
    for user in userList:
        studyTimeList.append((getDailyStudyTimeRank(user['userid']), counter))
        counter += 1
    studyTimeList.sort(key=takefirst, reverse=True)

    num = 10
    for i in range(num*page, min(num*(page+1),len(studyTimeList))):
        userdata={}
        userid = userList[studyTimeList[i][1]]['userid']
        user = User.objects.get(userid=userid)
        userdata['rank'] = i+1
        userdata['userid'] = user.userid
        userdata['username'] = user.username
        userdata['headImage'] = settings.ROOT_URL + user.headImage.url
        userdata['studytime'] = minuteTostr(studyTimeList[i][0])
        data.append(userdata)
    response['data'] = data
    response['ok'] = 1
    response['max'] = len(studyTimeList)
    return response


# 返回元组第一个元素
def takefirst(elem):
    return elem[0]


# 获取自习室的学习情况，也需要排行
def getRoomSituation(roomid, page):
    page = int(page)
    response = {'data': 0, 'ok': 0, 'msg': ''}
    infoList = Room.objects.filter(roomid=roomid)
    studyTimeList = []
    data = []
    counter = 0
    for info in infoList:
        studyTimeList.append((getDailyStudyTimeRank(info.userid.userid), counter))
        counter += 1
    studyTimeList.sort(key=takefirst, reverse=True)
    # print(studyTimeList)
    num = 10
    for i in range(num * page, min(num * (page + 1), len(studyTimeList))):
        userdata = {}
        userid = infoList[studyTimeList[i][1]].userid.userid
        user = User.objects.get(userid=userid)
        userdata['rank'] = i + 1
        userdata['userid'] = user.userid
        userdata['username'] = user.username
        userdata['headImage'] = settings.ROOT_URL + user.headImage.url
        userdata['studytime'] = minuteTostr(studyTimeList[i][0])
        userdata['entertime'] = infoList[studyTimeList[i][1]].jointime
        data.append(userdata)
    response['data'] = data
    response['ok'] = 1
    response['max'] = len(studyTimeList)
    response['limit'] = infoList[0].roommaxnum
    response['roomname'] = infoList[0].roomname
    response['roomid'] = infoList[0].roomid
    return response


def minuteTostr(minute):
    hours = minute//60
    if hours == 0:
        return str(str(minute)+'分')
    else:
        return str(str(hours)+'时'+str(minute-60*hours)+'分')
